package com.pay.interceptor;

import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.constants.WeixinConstants;
import com.pay.dubbo.wx.WxAccessTokenServiceFacade;
import com.pay.dubbo.wx.WxServiceFacade;
import com.pay.util.NeedOpenId;

/**
 * @Description: 微信拦截器获取openId
 * @see: SubscribeAnnotationInterceptor 此处填写需要参考的类
 * @version 2016年9月19日 上午10:47:20
 * @author shulin.feng
 */
@Repository
public class SubscribeAnnotationInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = LoggerFactory.getLogger(SubscribeAnnotationInterceptor.class);
	@Resource
	private WxServiceFacade wxServiceFacade;
	@Resource
	private WxAccessTokenServiceFacade wxAccessTokenServiceFacade;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod = null;
		try {
			handlerMethod = (HandlerMethod) handler;
		} catch (Exception e) {
			logger.error("handler--:{}", e);
		}
		if (handlerMethod == null) {
			// 如果请求地址错误则返回404的地址错误
			return super.preHandle(request, response, handler);
		}
		Method method = handlerMethod.getMethod();
		NeedOpenId annotation = method.getAnnotation(NeedOpenId.class);
		if (annotation == null) {
			return super.preHandle(request, response, handler);
		}

		// 判断请求方法是否需要检查关注
		boolean subscribeFlag = annotation.subscribeFlag();
		if (subscribeFlag) {
			String openId = (String) WebUtils.getSessionAttribute(request, WeixinConstants.sessionOpenIdKey);// 当前openid
			String accessToken = wxAccessTokenServiceFacade.getAccessToken();
			logger.info("判定关注页：openId：{},accessToken:{}", openId, accessToken);
			String userInfoJson = wxServiceFacade.getUserInfo(accessToken, openId);

			logger.info("请求授权获取微信用户信息返回结果：{}", userInfoJson);
			if (!StringUtils.isEmpty(userInfoJson)) {
				JSONObject weixinInfoJson = JSON.parseObject(userInfoJson);
				boolean containsKey = weixinInfoJson.containsKey("errcode");
				if (!containsKey) {
					String subscribe = weixinInfoJson.getString("subscribe");
					// 未关注
					if ("0".equals(subscribe)) {
						String indexUrl = "http://mp.weixin.qq.com/s?__biz=MzI4MTUwODg0OQ==&tempkey=EJauJ32pdiPLov1jVXsFmBkNYR6GBHaCrRWFx1w3zinOHTPp4OqHzGmAWe%2BdzGHCBmLBjBdA%2BBZIYjecT9YOfVZe99auPBNTWuvGlOmjjS20pdYPB16eRXdt4mSidC5koJRxMqYC66YFpYFp7Qp1ZQ%3D%3D&chksm=6ba96f955cdee6837c99df62c9726a85d5cae101f0661fbf794d94728ad45d5772b01c8fccb2#rd";
						logger.info("未关注跳转到关注页openId:{}",openId);
						response.sendRedirect(response.encodeRedirectURL(indexUrl));// 添加跳转到关注页地址
						return false;
					}
				}
			}
		}
		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
}
